package problem01;

import java.util.Stack;

/**
 * 问题一
 * 
 * @author Administrator
 *
 */
public class Stack_getMin <E extends Comparable<? super E>> {
	//数据栈
	private Stack<E> stackData;
	//保存最小值的栈
	private Stack<E> stackMin;

	public Stack_getMin() {
		stackData = new Stack<E>();
		stackMin = new Stack<E>();
	}
	public E push(E element) {
		stackData.push(element);
		if (stackMin.isEmpty()) {
			stackMin.push(element);
		} else {
			Comparable<? super E> min = this.getMin();
			if (min.compareTo(element) >= 0) {
				stackMin.push(element);
			}
		}
		return element;
	}
	public E pop() {
		E element = stackData.pop();
		if (!stackMin.empty()) {
			E min= this.getMin();
			if (element.compareTo(min) == 0) {
				stackMin.pop();
			}
		}
		return element;
	}

	public synchronized boolean isEmpty() {
		return stackData.isEmpty();
	}
	
	public E getMin(){
		if(stackMin.isEmpty()) return null;
		return stackMin.peek();
	}
	public static void main(String[] args) {

		Stack_getMin<Integer> stack = new Stack_getMin<Integer>();
		stack.push(3);
		stack.push(4);
		stack.push(1);
		stack.push(2);
		stack.push(5);
		while(!stack.isEmpty()){
			System.out.println(stack.getMin());
			System.out.println("------------------------------------");
			System.out.println(stack.pop());
		}
	}

}
